
#include "BScheduler.h"

using namespace blueberry;

BServer::BServer(UInt _uiPort,bool _bHB,UInt _uiServerID ,BServerCallback * _pSCB,BScheduler * _pEventMan):BItem(E_EVT_SERVER)
{
	ui_ServerPort = _uiPort;
	ui_ServerID = _uiServerID;
	p_ServerCB = _pSCB;
	p_EventMan = _pEventMan;
	b_HB =_bHB;
	b_IsDataLoggingEnabled = false;
}

BServer::~BServer()
{
	p_EventMan->AddToDeletedServerSet(ui_ServerID);
}
void BServer::CloseServerSocket()
{
	close(ui_ServerID);
}

void BServerCallback::OnData(BServer * _pServer, BClient * _pClient, char * _zData, int _iLen)
{
	_pServer = _pServer;
	_pClient = _pClient;
	_zData = _zData;
	_iLen = _iLen;
}
void BServerCallback::OnConnect(BServer * _pServer, BClient * _pClient)
{
	_pServer = _pServer;
	_pClient = _pClient;
}
void BServerCallback::OnDisconnect(BServer * _pServer, BClient * _pClient, BErr _Err)
{
	_pServer = _pServer;
	_pClient = _pClient;
	_Err = _Err;
}
void BServerCallback::OnReadyToSend(BServer * _pServer, BClient * _pClient)
{
	_pServer = _pServer;
	_pClient = _pClient;
}


void BServer::AddtoConnectedClientsList(BClient* _pClient)
{
	lst_ConnectedClients.push_back(_pClient);
}

void BServer::RemoveFromConnectedClientsList(BClient* _pClient)
{
	T_LST_CLIENTS::iterator ite = lst_ConnectedClients.begin();
	while( ite != lst_ConnectedClients.end())
	{
		if ( (*ite) == _pClient )
		{
			lst_ConnectedClients.erase(ite);
			break;
		}
		++ite;
	}
}

void BServer::SendToAllClients(const char * _zBuf, UInt _uiLen)
{
	T_LST_CLIENTS::iterator ite = lst_ConnectedClients.begin();
	while( ite != lst_ConnectedClients.end())
	{
		(*ite)->Send(_zBuf,_uiLen);
		++ite;
	}
}
